package cn.edu.ahtcm.servlet;

import cn.edu.ahtcm.bean.Article;
import cn.edu.ahtcm.mapper.ArticleMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/ArticleEditServlet")
public class ArticleEditServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        String title = request.getParameter("title");
        String content = request.getParameter("content");

        /*rticle article = new Article();
        //article.setId(id);
        article.setTitle(title);
        article.setContent(content);*/

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ArticleMapper articleMapper = sqlSession.getMapper(ArticleMapper.class);
        Article article = articleMapper.selectById(id);
        sqlSession.commit();
        sqlSession.close();
        if(article!=null){
            request.setAttribute("article",article);
            System.out.println(article.getTitle());
            //页面转发到编辑界面
            request.getRequestDispatcher("/admin/articleEdit.jsp").forward(request,response);
        }else{
            request.setAttribute("error","文章编辑失败");
            request.getRequestDispatcher("/error.jsp").forward(request,response);
        }

    }



    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
